<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/11/18
 * Time: 16:52
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);

namespace app\api\controller;

use app\common\business\PlaceOrder;
use app\common\lib\Show;
use EasyWeChat\Factory;
use think\facade\Log;

class Notify extends Base
{
    /**
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function jsapi()
    {
        $app = Factory::payment(config('wechat.miniPay'));
        $response = $app->handleScannedNotify(function ($message, $fail) {
            Log::info("订单{$message['out_trade_no']}开始处理");

            Log::order(Show::json_encode($message));
            $order = (new PlaceOrder())->getOrderByOrderId($message['out_trade_no']);
            if ($order) {
                if ($order['payStatus'] != 0) {
                    return true;
                }
                if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                    // 用户是否支付成功
                    $update_data = [];
                    if ($message['result_code'] === 'SUCCESS') {
                        $update_data = [
                            "update_time" => time(),
                            "payTime" => strtotime($message['time_end']),
                            "payStatus" => 1
                        ];
                        // 用户支付失败
                    } else if ($message['result_code'] === 'FAIL') {
                        $update_data = [
                            "update_time" => time(),
                            "payStatus" => 2
                        ];
                    }

                    $res = $order->save($update_data);
                    if($res){
                        Log::info("订单{$message['out_trade_no']}处理完成");
                        return true;
                    }else{
                        Log::error("订单{$message['out_trade_no']}处理完成!更新数据库失败");
                        return $fail('更新数据库失败!请稍后通知我');
                    }
                } else {
                    return $fail('通信失败，请稍后再通知我');
                }

            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            //Log::info(Show::json_encode($message));
        });
        return $response;
    }
}